package cn.daniellee.plugin.command;

import cn.daniellee.plugin.PokeEditFilter;
import com.google.gson.Gson;
import com.pixelmonmod.pixelmon.Pixelmon;
import com.pixelmonmod.pixelmon.api.pokemon.Pokemon;
import com.pixelmonmod.pixelmon.storage.PlayerPartyStorage;
import com.pixelmonmod.pixelmon.util.PixelmonPlayerUtils;
import net.minecraft.entity.player.EntityPlayerMP;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.List;

public class FilterCommand implements CommandExecutor {

	@Override
	public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
		if (strings.length >= 3) {
			Player player = Bukkit.getPlayer(strings[0]);
			if (player != null && !commandInterceptor(player, strings[0], Integer.parseInt(strings[1].replaceAll("[^0-9]", "")))) {
				Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "pokeedit " + StringUtils.join(strings, " "));
			}
		}
		return true;
	}

	private boolean commandInterceptor(Player target, String playerName, int slot) {
		EntityPlayerMP player = PixelmonPlayerUtils.getUniquePlayerStartingWith(playerName);
		if (player == null) {
			target.sendMessage((PokeEditFilter.prefix + PokeEditFilter.config.get("invalid-player")).replace("&", "§"));
			return true;
		}
		PlayerPartyStorage playerStorage = Pixelmon.storageManager.getParty(player);
		if (slot < 1 || slot > 6) {
			target.sendMessage((PokeEditFilter.prefix + PokeEditFilter.config.get("wrong-slot-number")).replace("&", "§"));
			return true;
		}
		Pokemon pokemon = playerStorage.get(slot - 1);
		if (pokemon == null) {
			target.sendMessage((PokeEditFilter.prefix + PokeEditFilter.config.get("slot-empty")).replace("&", "§"));
			return true;
		}
		String name = pokemon.getSpecies().getLocalizedName();
		List<String> list = PokeEditFilter.config.getStringList("list");
		if (list != null && !list.isEmpty()) {
			for (String item : list) {
				if (item.equals(name)) {
					target.sendMessage((PokeEditFilter.prefix + PokeEditFilter.config.get("pixelmon-ban")).replace("&", "§"));
					return true;
				}
			}
		}
		return false;
	}

}
